const dataBase = require('../database')


// 获取当前用户信息
function getUser(req, res){
    // 定义一条查询当前登入的用户信息
    const SelestUser = 'select id, username, name, age, sex, birthday, address, usertype from user where userName = ?'
    const username = req.body.username

    dataBase.query(SelestUser, username, (err, results) => {
        if(err){
            res.send({
                status: 404,
                message: '获取信息失败！'
            })
        }else{
            res.send({
                status: 200,
                message: '获取成功',
                user: results[0]
            })
        }
    })

}



// 获取所有普通用户的信息
function getUsers(req, res){

    // 定义一条查询 user 表所以数据的 SQL
    const SelectUsers = "select id, username, name, age, sex, birthday, address, usertype from user where usertype != '2'"

    // 使用 dataBase 进行访问 user 表中的数据
    dataBase.query(SelectUsers, (err, results) => {
        if(err){
            res.send({
                status: 404,
                message: '获取信息失败！'
            })
        }else{
            res.send({
                status: 200,
                message: '获取成功',
                users: results
            })
        }
    })
}


// 获取用户购物车数据
function getShoppingCartInfo(req, res){

    // 定义一条根据 用户账号 获取用户购物车数据的 SQL
    const getShoppingCartInfoSql = "select mygoods.id as 'mygoodsId', g.id as 'id', goodsname, goodstype, goodsInfo, goodsImg, goodsprice, goodsNum from mygoods join goods g on g.id = mygoods.goodsId join user u on u.id = mygoods.userId where userName = ?"

    dataBase.query(getShoppingCartInfoSql, req.body.username, (err, results) => {
        if(err){
            return res.send({
                status: 404,
                message: '获取信息失败！'
            })
        }

        if(results.length <= 0){
            return res.send({
                status: 404,
                message: '暂无数据！'
            })
        }

        res.send({
            status: 200,
            data: results
        })
    })
}

module.exports = {
    getUsers,
    getUser,
    getShoppingCartInfo
}